package com.bangcommunity.bbframe.sdm.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class CommonApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;// 声明一个静态变量保存
    static Logger logger = LoggerFactory.getLogger(CommonApplicationContextUtil.class);

    @Override
    @SuppressWarnings("static-access")
    public void setApplicationContext(ApplicationContext contex) throws BeansException {
        logger.info("ApplicationContext init..." + contex);
        CommonApplicationContextUtil.context = contex;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    @SuppressWarnings("unchecked")
    public static <E> E getBean(String name) {
        if (context.containsBean(name)) {
            return (E) context.getBean(name);
        } else {
            return null;
        }
    }

    public static String getEvnProperty(String key) {
        return context.getEnvironment().getProperty(key);
    }
}